/*
 * @description:
 * @version: 1.0.1
 * @Author: xuqiulin
 * @Date: 2021-05-01 10:44:53
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-05-01 15:18:17
 */
package controllers

import (
	"net/http"

	"cmt1-admin/conf"
	"cmt1-admin/db/mongodb"

	"github.com/gin-gonic/gin"
)

var (
	GameDB      *mongodb.MgoSession
	GameLogDB   *mongodb.MgoSession
	GameAdminDB *mongodb.MgoSession
)

func InitDB(c *conf.Config) {
	var err error
	GameDB, err = mongodb.NewMgoSession(c.Game)
	if err != nil {
		panic(err)
	}

	GameLogDB, err = mongodb.NewMgoSession(c.GameLog)
	if err != nil {
		panic(err)
	}

	GameAdminDB, err = mongodb.NewMgoSession(c.GameAdmin)
	if err != nil {
		panic(err)
	}
}

func handleErr(c *gin.Context, code int, message string) {
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"message": message,
	})
}

func handleOk(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    data,
	})
}

////// 跨域
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin") //请求头部

		if origin != "" {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", "*")                                        // 这是允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			//  header的类型
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			//              允许跨域设置                                                                                                      可以返回其他子段
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                           // 缓存请求信息 单位为秒
			c.Header("Access-Control-Allow-Credentials", "false")                                                                                                                                                  //  跨域请求是否需要带cookie信息 默认设置为true
			c.Set("content-type", "application/json")                                                                                                                                                              // 设置返回格式是json
		}
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		// 处理请求
		c.Next() //  处理请求
	}
}

type BaseRequest struct {
	Page    int `form:"page"`
	PageNum int `form:"pageNum"`
}
